<?php

namespace liketp\response;

use finfo;
use liketp\Response;

class File extends Response
{
    protected $contentType = 'image/jpep';
    protected $name;

    public function __construct($data, int $code = 200)
    {
        $data = $this->getAndCheck($data);
        $this->init($data, $code);
    }

    public function output($data)
    {
        $name = $this->name ?: $this->getFileName();
        $mime = $this->getMimeType();
        $fileSize = filesize($data);

        $this->header('Content-Type', $mime);
        $this->header('Content-Length', $fileSize);
        $this->header('Content-Disposition', 'filename=' . $name);

        $data = file_get_contents($data);
        return $data;
    }

    public function name(string $name)
    {
        $this->name = $name;
        return $this;
    }

    //------------------------------------------------ protected
    protected function getAndCheck($data)
    {
        if ($data instanceof \Closure) {
            $data = $data();
        }
        if (is_string($data) && file_exists($data)) {
            return $data;
        } else {
            throw new \Exception('File is not exists');
        }
    }

    protected function getFileName()
    {
        return pathinfo($this->data, PATHINFO_BASENAME);
    }

    protected function getMimeType()
    {
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        return $finfo->file($this->data);
    }
}
